package com.xh.pmo.db;

import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;
import org.logicalcobwebs.proxool.admin.SnapshotIF;
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;

/*
 * 连接池信息
 * 
 */
public class ConnectionFactory {

	private static int activeCount = 0;

	//private static ConnectionFactory pm = new ConnectionFactory();

	public  Connection getConnect() {
		return getConnection();
	}

	public Session getSession() {
		
		return new Session(getConnect());
	}
	// 构造方法私有，不允许外部直接new该对象，以保证只有一个该对象的实例。
	public ConnectionFactory() {
		System.out.println("初始化 连接工厂");
		
		String fileName = "proxool.xml";
		URL resourceURL = null;
		try {
			if (Thread.currentThread().getContextClassLoader() != null) {
				resourceURL = Thread.currentThread().getContextClassLoader()
						.getResource(fileName);
			}
			if (resourceURL == null) {
				resourceURL = ConnectionFactory.class.getClassLoader().getResource(
						fileName);
			}

			Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
			JAXPConfigurator.configure(resourceURL.getFile(), false);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} // proxool驱动类
		catch (ProxoolException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获取连接 getConnection
	 * 
	 * @param name
	 * @return
	 */
	public Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection("proxool.PMO");
			// 此处的DBPool是在proxool.xml中配置的连接池别名
			return conn;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	/**
	 * 此方法可以得到连接池的信息 showSnapshotInfo
	 */
	public void showSnapshotInfo() {
		try {
			SnapshotIF snapshot = ProxoolFacade.getSnapshot("PMO", true);
			int curActiveCount = snapshot.getActiveConnectionCount();// 获得活动连接数
			int availableCount = snapshot.getAvailableConnectionCount();// 获得可得到的连接数
			int maxCount = snapshot.getMaximumConnectionCount();// 获得总连接数
			
			if (curActiveCount != activeCount) { // 当活动连接数变化时输出的信息
				System.out.println("活动连接数:" + curActiveCount
						+ "(active) 可得到的连接数:" + availableCount
						+ "(available) 总连接数:" + maxCount + "(max)");
				activeCount = curActiveCount;
			}
		} catch (ProxoolException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 释放连接 freeConnection
	 * 
	 * @param conn
	 */
	public static void close(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}